<!-- <template>
  <view class="product-bg">
    <swiper 
      :indicator-dots="indicatorDots" 
      indicator-active-color="#fff" 
      :autoplay="autoplay"
      :circular="circular" 
      :interval="interval" 
      :duration="duration" 
      @change="change"
    > 
      <block v-for="(item, index) in mediaList" :key="index">
        <swiper-item> 
          <view v-if="item.type === 'image'"  class="item"> 
            <image :src="ossUrl + item.url " class="slide-image" />
          </view> 
          <view v-else-if="item.type === 'video'" class="item">
        
            <view v-if="!controls" style="width: 100%; height: 100%;">
              <video 
                id="video_{{index}}" 
                :src="ossUrl + item.url" 
                objectFit="cover" 
                controls 
                style="width: 100%; height: 100%;" 
                :poster="ossUrl + item.url + '?vframe/jpg/offset/1'"
                @pause="videoPause(index)" 
              ></video>
            </view>
        
            <view class="poster" v-if="controls">
              <image class="image" :src="ossUrl + item.url + '?vframe/jpg/offset/1'" />
            </view>
          
            <view class="stop" v-if="controls" @tap="bindPause(index)"> 
              <tui-icon :size="64" color="#fff" name="play"></tui-icon> 
            </view>
          </view>
        </swiper-item>
      </block>
    </swiper>
  </view>
</template> -->

<template>
	<view class="product-bg">
		<!-- 动态绑定swiper高度 -->
		<swiper :style="{ height: currentSwiperHeight + 'px' }" @change="handleSwiperChange" :current="currentIndex"
			:indicator-dots="indicatorDots" indicator-active-color="#fff" :autoplay="autoplay" :circular="circular"
			:interval="interval" :duration="duration">
			<block v-for="(item, index) in mediaList" :key="index">
				<swiper-item class="swiper-item" :id="'swiperItem_' + index">
					<!-- 图片项 -->
					<view v-if="item.type === 'image'" class="item">
						<image :src="ossUrl + item.url" mode="aspectFill" class="slide-image"
							@load="() => handleMediaLoad(index)" />
					</view>

					<!-- 视频项 -->
					<!-- <view v-else-if="item.type === 'video'" class="item"> 
			  <video 
				v-if="!controls"
				:id="'video_' + index"
				:src="ossUrl + item.url"
				:poster="ossUrl + item.url + '?vframe/jpg/offset/1'"
				controls
				style="width: 100%; height: 100%;"
				@pause="videoPause(index)"
			  />
			   
			  <view v-if="controls" class="poster">
				<image 
				  :src="ossUrl + item.url + '?vframe/jpg/offset/1'"
				  mode="widthFix"
				  class="cover-image" 
				  @load="handleMediaLoad(index)"
				/>
			  </view>
			   
			  <view v-if="controls" class="stop" @tap="bindPause(index)"> 
				<tui-icon :size="64" color="#fff" name="play"></tui-icon> 
			  </view>
			</view> -->
				</swiper-item>
			</block>
		</swiper>
	</view>
</template>

<script>
	export default {
		props: {
			imgUrls: {
				type: Array,
				default: function() {
					return [];
				}
			},
			videoline: {
				type: String,
				value: ""
			},
			ossUrl: {
				type: String,
				value: ""
			}
		},
		watch: {
			imgUrls(val) {
				if (val && !this.videoline) {
					let arr = []
					arr = this.imgUrls.map(item => {
						return {
							type: 'image',
							url: item
						}
					})
					this.mediaList = arr
				}
			},
			videoline(val) {
				if (val && this.imgUrls) {
					let arr = []
					arr = this.imgUrls.map(item => {
						return {
							type: 'image',
							url: item
						}
					})
					arr.push({
						type: 'video',
						url: val
					})
					this.mediaList = arr
				} else {
					this.mediaList = [{
						type: 'video',
						url: val
					}]
				}

			}
		},
		data() {
			return {
				indicatorDots: true,
				circular: true,
				autoplay: true,
				interval: 3000,
				imageUrl: 'https://oss.starbounce.cn/2025/01/05/274a6fd51f8b4c2280ba3d43c17c1f06.jpg',
				duration: 500,
				currents: "1",
				controls: true,
				isPlay: true,
				videoContext: null,
				mediaList: [],
				currentSwiperHeight: 300, // 初始高度（根据需求调整）
				mediaHeights: [], // 缓存所有媒体项的高度
				currentIndex: 0 // 当前显示项的索引
			};
		},
		onReady() {
			this.calculateHeight(0).then(height => console.log(height, '高度'));
		},
		methods: {
			// 统一处理媒体加载
			handleMediaLoad(index) {
				this.$nextTick(() => {
					this.calculateHeight(index).then(height => {
						this.mediaHeights[index] = height
						if (index === this.currentIndex) {
							this.currentSwiperHeight = height
						}
					}).catch(err => {});
				})
			},

			// H5环境专用高度计算
			calculateHeight(index) {
				return new Promise(resolve => {
					const query = uni.createSelectorQuery().in(this.$scope)
					const selector = `#swiperItem_${index} .item .slide-image`;
					query.select(selector)
						.boundingClientRect(res => {
							console.log(res.height, 'res')
							if (res && res.width) {
								// 计算逻辑优化：避免NaN问题
								const height = res.height || res.width * (res.height / res.width || 0.75); // 默认宽高比0.75
								resolve(Math.ceil(height))
							} else {
								resolve(200) // 默认高度
							}
						}).exec();
				})
			},

			// 处理swiper切换
			handleSwiperChange(e) {
				const newIndex = e.detail.current
				this.currentIndex = newIndex
				if (this.mediaHeights[newIndex]) {
					this.currentSwiperHeight = this.mediaHeights[newIndex]
				} else {
					this.calculateHeight(newIndex).then(height => {
						this.currentSwiperHeight = height
					})
				}
			},

			videoPause(index) {
				const videoContext = uni.createVideoContext(`video_${index}`, this);
				videoContext.pause(); // 暂停视频
				this.$set(this, 'controls', true);
			},
			bindPause(index) {
				const videoContext = uni.createVideoContext(`video_${index}`, this); // 创建 videoContext
				videoContext.play(); // 播放视频
				videoContext.requestFullScreen({
					direction: 0
				}); // 全屏播放
				this.$set(this, 'controls', false);
				this.autoplay = false;
			},
			change(e) {
				this.currents = e.detail.current + 1;
				this.$set(this, 'controls', true); // 每次滑动时重置控制状态
			}
		}
	}
</script>
<style scoped>
	/* H5专用样式 */
	.product-bg {
		width: 100%;
		overflow: hidden;
	}

	swiper {
		width: 100%;
		transition: height 0.3s ease;
		/* 添加过渡动画 */
		overflow: visible !important;
		/* H5必须 */
	}

	.swiper-item {
		height: 600rpx;
		display: block !important;
		position: relative;
		box-sizing: border-box;
	}

	.slide-image,
	.cover-image {
		width: 100%;
		display: block;
		vertical-align: top;
	}


	/* 视频容器高度继承 */
	.poster {
		width: 100%;
		position: relative;
	}

	/* 播放按钮定位调整 */
	.stop {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 10;
	}
</style>